# Copyright (C) 2025 All rights reserved.
#   
# @File message.py
# @Brief 
# @Author 杨嘉祥, vnimy@mediad.cn
# @Version 1.0
# @Date 2025-01-26
#
import frappe
from frappe import _
from frappe.core.doctype.user.user import generate_keys
from frappe_wxwork.oauth2_logins import get_wx_corpid_secret
from frappe.utils.oauth import get_oauth_keys
from frappe.utils.password import get_decrypted_password
from .wxworkapi.CorpApi import *
import requests
import json


@frappe.whitelist(allow_guest=True)
def callback():
    pass

@frappe.whitelist()
def send_wxwork_message(users, doc):
    #doc = frappe._dict(doc)
    message_type = doc.message_type.lower() 
    # 优先直接发到供应商聊天群，如果有供应商且维护了webhook
    if doc.get("supplier"):
        if webhook_key := frappe.db.get_value("Supplier", doc.supplier, "wxwork_chat_group_webhook"):
            send_notification_to_group(webhook_key, doc.content, message_type)
            return
    
    corpid, corpsecret = get_wx_corpid_secret()
    if not corpid: return
    settings = frappe.get_single("WXWork Settings")
    agentid = frappe.db.get_value("Social Login Key", settings.social_login_key, "wxwork_agentid")
    api = CorpApi(corpid, corpsecret)

    userids = frappe.get_list("WXWork User", {"corpid": corpid, "user": ["in", users]}, pluck="userid")
    for userid in userids:        
        data = {
            "touser": userid,
            "agentid": agentid,
            "safe": 0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800,
        }
            
        data.update(
            {
                "msgtype": message_type,
                message_type: {"content": doc.content},
            }
        )
        
        response = api.httpCall(CORP_API_TYPE["MESSAGE_SEND"], data)
            # msgid = response.get("msgid")


class WXWorkWebhook:
    def __init__(self, webhook_key=None):
        self.webhook_key = webhook_key  # or "05278936-c111-4d66-8941-b533b55d3529"
        self.base_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send"
    
    @property
    def webhook_url(self):
        return f"{self.base_url}?key={self.webhook_key}"
    
    def send_text(self, content, mentioned_list=None, mentioned_mobile_list=None):
        """发送文本消息"""
        data = {
            "msgtype": "text",
            "text": {
                "content": content
            }
        }
        
        if mentioned_list:
            data["text"]["mentioned_list"] = mentioned_list
        if mentioned_mobile_list:
            data["text"]["mentioned_mobile_list"] = mentioned_mobile_list
            
        return self._send_message(data)
    
    def send_markdown(self, content):
        """发送markdown消息"""
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": content
            }
        }
        return self._send_message(data)
    
    def send_image(self, image_base64, md5):
        """发送图片消息"""
        data = {
            "msgtype": "image",
            "image": {
                "base64": image_base64,
                "md5": md5
            }
        }
        return self._send_message(data)
    
    def send_news(self, articles):
        """发送图文消息"""
        data = {
            "msgtype": "news",
            "news": {
                "articles": articles
            }
        }
        return self._send_message(data)
    
    def _send_message(self, data):
        """发送消息的底层方法"""
        try:
            response = requests.post(
                self.webhook_url,
                headers={"Content-Type": "application/json"},
                data=json.dumps(data),
                timeout=10
            )
            result = response.json()
            
            if result.get("errcode") == 0:
                frappe.logger().info(f"企业微信群消息发送成功: {data.get('msgtype')}")
                return True
            else:
                frappe.log_error(f"企业微信群消息发送失败: {result.get('errmsg')}"[:140], frappe.get_traceback(with_context=True))
                return False
                
        except Exception as e:
            frappe.log_error(f"企业微信群消息发送异常: {str(e)}"[:140], frappe.get_traceback(with_context=True))
            return False

@frappe.whitelist()
def send_notification_to_group(webhook_key, content, message_type="text", mentioned_mobile_list=None):
    """向群聊发送通知的便捷函数"""
    webhook = WXWorkWebhook(webhook_key)
    
    if message_type == "markdown":
        return webhook.send_markdown(content)
    else:
        return webhook.send_text(content, mentioned_mobile_list=mentioned_mobile_list)

# 在DocType中使用的例子
def on_update_after_save(doc, method):
    """在文档保存后发送通知到企业微信群"""
    if doc.workflow_state == "Approved":
        content = f"文档 {doc.name} 已审核通过\n\n创建人: {doc.owner}\n时间: {frappe.utils.now()}"
        send_notification_to_group(content, "text")
    
    elif doc.workflow_state == "Rejected":
        content = f"❌ 文档 {doc.name} 被拒绝\n\n**原因**: {doc.reason or '未说明原因'}\n**处理人**: {doc.modified_by}"
        send_notification_to_group(content, "markdown")